package thread;

import java.util.concurrent.CountDownLatch;

/**
 * @author Mr.Sun
 * @date 2022年03月09日 21:17
 *
 * 测试闭锁
 */
public class TestHarness {

    /**
     * 测试n个线程并发执行任务所需要的时间
     * @param threadNum 线程数
     * @param task 任务
     * @return 消耗时间
     * @throws InterruptedException
     */
    public static long timeTasks(int threadNum, final Runnable task) throws InterruptedException {
        final CountDownLatch startGate = new CountDownLatch(1);
        final CountDownLatch endGate = new CountDownLatch(threadNum);

        for (int i = 0; i < threadNum; i++) {
            Thread t = new Thread(() -> {
                try {
                    startGate.await();
                    try {
                        task.run();
                    } finally {
                        endGate.countDown();
                    }
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            });
            t.start();
        }

        long start = System.nanoTime();
        startGate.countDown();
        endGate.await();
        long end = System.nanoTime();
        return end - start;
    }

    public static void main(String[] args) throws InterruptedException {
        long time = timeTasks(3, () -> System.out.println(Thread.currentThread().getName()));
        System.out.println(time);
    }


}
